﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using ZSZ.Iservice;

namespace ZSZ.QianWeb.App_Start
{
    public class QianHelper
    {
        public static long? GetUserId(HttpContextBase context)
        {
            return (long?)context.Session["UserId"];
        }
        public static long? GetCityId(HttpContextBase context)
        {
            long? userId = GetUserId(context);
            ICityService cityService = DependencyResolver.Current.GetService<ICityService>();
            IUserService userService = DependencyResolver.Current.GetService<IUserService>();
            if (userId == null)
            {
                return cityService.GetAll()[0].Id;
            }
            long? cityId =  userService.GetById((long)userId).CityId;
            if (cityId==null)
            {
                return cityService.GetAll()[0].Id;
            }
            return cityId;
        }
        public static string ToQueryString(NameValueCollection queryString) {
            StringBuilder sb = new StringBuilder();
            foreach (var item in queryString.AllKeys)
            {
                sb.Append(item).Append("=").Append(Uri.EscapeDataString(queryString[item])).Append("&");
            }
            return sb.ToString().Trim('&');
        }
        public static string RemoveQueryString(NameValueCollection queryString,string can) {
            NameValueCollection nameValue = new NameValueCollection(queryString);
            nameValue.Remove(can);
            return ToQueryString(nameValue);
        }
        public static string UpdateQueryString(NameValueCollection queryString,string can,string zhi) {
            NameValueCollection nameValue = new NameValueCollection(queryString);
            if (nameValue.AllKeys.Contains(can))
            {
                nameValue[can] = zhi;
            }
            else {
                nameValue.Add(can,zhi);
            }
            return ToQueryString(nameValue);
        }
    }
}